package com.guanjialhx.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyHttpUtil {

    /**
     * 发起批量转账API 批量转账到零钱
     *
     * @param requestUrl
     * @param requestJson       组合参数
     * @param wechatPayserialNo 商户证书序列号
     * @param mchID4M           商户号
     * @param privatekeypath    商户私钥证书路径
     * @return
     */
    public static String postTransBatRequest(
            String requestUrl,
            String requestJson,
            String wechatPayserialNo,
            String mchID4M,
            String privatekeypath) {

        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) new URL(requestUrl).openConnection();
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Wechatpay-Serial", wechatPayserialNo);
            //获取token
            String token = VechatPayV3Util.getToken("POST", "/v3/transfer/batches", requestJson, mchID4M, wechatPayserialNo, privatekeypath);
            System.out.println("微信转账的token===" + token);
            con.setRequestProperty("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + token);
            con.setReadTimeout(3000);
            con.setConnectTimeout(3000);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            //携带参数
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), "utf-8"));
            writer.write(requestJson);
            writer.close();

            con.connect(); //连接

            int code = con.getResponseCode();
            String line;
            StringBuilder builder = new StringBuilder();
            BufferedReader buffer = null;
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                //将响应流转换成字符串
                builder = new StringBuilder();
                buffer = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                while ((line = buffer.readLine()) != null) {
                    builder.append(line);
                }
                return builder.toString();
            } else {
                buffer = new BufferedReader(new InputStreamReader(con.getErrorStream(), "utf-8"));      //code ！= 200的时候还能返回
                while ((line = buffer.readLine()) != null) {
                    builder.append(line);
                }
                return builder.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return null;
    }
}
